/*
 * Design Assignment2.c
 *
 * Created: 2014/3/1 15:43:13
 *  Author: Rong Xue
 */ 

#define F_CPU 1000000UL	  /* prevent compiler error by supplying a default */
#include <util/delay.h>   // include library for delay purpose
#include <avr/interrupt.h> //include library for interrupt purpose 
#include <avr/io.h>

int volatile TMP=0;  //volatile variable for unstable counter 

void delayfc();  // delay function prototype  


int main(void)  // main function
{
int cnt=0; // declaration of counter variable 
DDRD = 0b1011; // DDRD(0,1,3) as output
DDRB = 0xFF; // make DDRB as output
sei(); // command for interrupts
EICRA =(1<<ISC01); // set interrupt on ISC01
EIMSK =(1<<INT0); // enable INT0


    while(1)
    {
        delayfc(); //run delay function
		if(PORTD&(1<<PD0)) // loop if port 0 is set
		{
		delayfc(); // start delay 
		PORTB = ++cnt; // counter will course toggle on PD0's falling edge
		if(cnt>=225) // if counter reach 255 reset counter
			cnt=0; // reset counter
		if((cnt%20)==0) //turn on PD1 led for every 1pth falling purlse reached
			PORTD ^=1<<PD1;	 // turn on PD1 LED
		}
		
	}

    
}

ISR (INT0_vect) // ISR function used for interrupt purpose
{
	TMP++;  // increase global counter
	if(TMP ==2){ //if counter equal 2 turn on PD3 and reset counter
		PORTD = (1<<PD3);
		TMP=0;
	}
}

void delayfc() // delay function 
{
	_delay_ms(250.0); // delay time is 250ms per cycle which is 500ms(or0.5 sec) per period
	PORTD ^= 1<<PD0; // toggle PD 0 after delay
}